package com.bowos.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
@Lazy(false)
public class SpringUtils implements ApplicationContextAware {
	@SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> c){
		Object[] beans = getApplicationContext().getBeansOfType(c).values().toArray();
		if(beans.length >= 1)
			return (T) beans[0];
		else
			return null;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T[] getBeans(Class<T> c){
		Object[] beans = getApplicationContext().getBeansOfType(c).values().toArray();
		if(beans.length >= 1)
			return (T[]) beans;
		else
			return null;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String c){
		return (T) getApplicationContext().getBean(c);
	}
	
	public static ApplicationContext getApplicationContext(){
		return context;
//		return (ApplicationContext) ServletUtils.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	}
	
	public static ApplicationContext context = null;

	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		SpringUtils.context = context;
	}
}
